package com.fingard.dsp.bank.directbank.mufg01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.Date;

/**
 * 三菱香港
 *
 * @version 1.0
 */
public class MUFG01Transaction extends MUFG01Base implements ITransaction {

    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        return "1".equals(getBankConfig().getValueAsString("channelFlag")) ? d_7516_HisTrans_Xml(p_req7516) : d_7516_HisTrans_MT(p_req7516);
    }

    public RetAtsTrans d_7516_HisTrans_MT(Req7516HisTrans p_req7516) throws Exception {
        //查询时间校验
        String[] dateAry = getQueryDate(p_req7516.dateFrom, p_req7516.dateTo);
        p_req7516.dateFrom = dateAry[0];
        p_req7516.dateTo = dateAry[1];
        //查询明细数据
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();
        try {
            String accountNum = p_req7516.actNum;
            Date dateStart = Format.Date8Format.parse(p_req7516.dateFrom);
            Date dateEnd = Format.Date8Format.parse(p_req7516.dateTo);
            Calendar calendar = Calendar.getInstance();
            while (!dateStart.after(dateEnd)) {
                String dealedPath = getBankConfig().getValueAsString("DealedPath") + File.separator +
                        Format.Date8Format.format(dateStart) + File.separator + "MT940" + File.separator +
                        accountNum + "_7516.txt";
                if (!FileHelper.existFile(dealedPath)) {
                    calendar.setTime(dateStart);
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    dateStart = calendar.getTime();
                    continue;
                }
                String readLine = "";
                InputStreamReader isr = null;
                FileInputStream fis = null;
                BufferedReader reader = null;
                try {
                    fis = new FileInputStream(dealedPath);
                    isr = new InputStreamReader(fis, getCharset());
                    reader = new BufferedReader(isr);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                } finally {
                    if (fis != null) {
                        fis.close();
                    }
                    if (isr != null) {
                        isr.close();
                    }
                    if (reader != null) {
                        reader.close();
                    }
                }
                while ((readLine = reader.readLine()) != null) {
                    //账号 | 币种 | 交易日期| 交易时间| 计息日期 | 交易金额 |借贷标识| 账户余额 |对方账号|
//                    对方户名 | 对方银行 |用途| 流水号|
                    String[] transDetail = readLine.split("\\|");
                    if (transDetail.length > 12) {
                        RetAtsTransDetail retDetail = new RetAtsTransDetail();
                        retDetail.actArea = p_req7516.actArea;
                        retDetail.actNum = transDetail[0].trim();
                        retDetail.cur = convertCurToATS(transDetail[1].trim());
                        retDetail.tranDate = transDetail[2].trim();
                        retDetail.tranTime = transDetail[3].trim();
                        retDetail.valueDate = transDetail[4].trim();
                        retDetail.tranAmt = transDetail[5].trim();
                        retDetail.recAccNum = transDetail[8].trim();
                        retDetail.cdFlag = "C".equals(transDetail[6].trim()) ? "2" : "1";
                        retDetail.accBal = transDetail[7].trim();
                        retDetail.recAccName = transDetail[9].trim();
                        retDetail.recAccBank = transDetail[10].trim();
                        String[] transArray = transDetail[11].split("##");
                        if (transArray.length > 1) {
                            if (transArray[0].trim().length() > 256) {
                                retDetail.usage = transArray[0].trim().substring(0, 256);
                                retDetail.comment = transArray[0].trim().substring(256) + " " + transArray[1];
                            } else {
                                retDetail.usage = transArray[0].trim();
                                retDetail.comment = transArray[1];
                            }
                        } else {
                            if (transArray[0].trim().length() > 256) {
                                retDetail.usage = transArray[0].trim().substring(0, 256);
                                retDetail.comment = transArray[0].trim().substring(256);
                            } else {
                                retDetail.usage = transArray[0].trim();
                            }
                        }
                        retDetail.askNumber = transDetail[12].trim();
                        retAts.writeRetDetail(retDetail);
                    }
                }
                reader.close();
                calendar.setTime(dateStart);
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                dateStart = calendar.getTime();
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
            WriteBankLogLn("查询历史明细异常：" + e);
        }
        if ("-1".equals(tmpRespCode)) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("明细为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    public RetAtsTrans d_7516_HisTrans_Xml(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        retAtsTrans.writeStart();
        String tmpRespCode = "";
        String tmpRespInfo = "";
        try {
            //起始日期
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            //结束日期
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while (tmpIntDateFrom <= tmpIntDateTo) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //当是跨月查询时，先查询起始日期到月末日期记录，再查询月末后一天日期到结束日期记录
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                String pageFlag = "";//下一页标识
                boolean pageResult = false;//分页结束标识
                while (!StringHelper.isNullOrEmpty(pageFlag) || !pageResult) {
                    //拼接请求报文体
                    MUFG01Header header = new MUFG01Header();
                    header.transCode = "h2h.001.002";
                    header.pkgNo = getQryTransID();
                    XmlTextWriter xmlReq = new XmlTextWriter();
                    writeReqHeader(xmlReq, header);
                    XElement body = new XElement("req", "");
                    body.addChild(new XElement("accNo", p_req7516.actNum));//账号
                    body.addChild(new XElement("beginDate", Format.Date10Format.format(tmpCalendarFrom.getTime())));//开始时间
                    body.addChild(new XElement("endDate", Format.Date10Format.format(tmpClndrStepTo.getTime())));//结束时间
                    body.addChild(new XElement("pageFlag", pageFlag));//下一页标识
                    xmlReq.writeXElement(body);
                    xmlReq.writeEndDocument();
                    //发送请求报文
                    String[] resutlt = sendToBank(xmlReq.toXmlString());
                    //处理响应报文
                    if (resutlt[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(resutlt[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String acceptFlag = tmpBkReader.getFirstText("/h2h/respInfo/acceptFlag");//报文受理状态
                            String respCode = tmpBkReader.getFirstText("/h2h/respInfo/respCode");//返回结果码
                            String respInfo = tmpBkReader.getFirstText("/h2h/respInfo/respMsg");//返回结果说明
                            if ("1".equals(acceptFlag)) {//受理成功
                                String pageFlagRsp = tmpBkReader.getFirstText("/h2h/resp/pageFlag");//下一页标识
                                if (!StringHelper.isNullOrEmpty(pageFlagRsp)) {
                                    pageFlag = pageFlagRsp;
                                } else {
                                    pageResult = true;
                                }
                                if ("1".equals(tmpBkReader.getFirstText("/h2h/resp/statusFlag"))) {//查询处理状态 1有 -1无
                                    while (tmpBkReader.read("/h2h/resp/row")) {
                                        XElement readXElement = tmpBkReader.readedXElement;
                                        RetAtsTransDetail detail = new RetAtsTransDetail();
                                        detail.actArea = p_req7516.actArea;
                                        detail.actNum = p_req7516.actNum;
                                        detail.tranDate = readXElement.getSingleTextNotNull("bookDate").trim();
                                        detail.valueDate = readXElement.getSingleTextNotNull("valueDate").trim();
                                        detail.tranTime = detail.valueDate + " 00:00:00";
                                        detail.cur = convertCurToATS(readXElement.getSingleTextNotNull("currCode").trim());//币种
                                        detail.accBal = readXElement.getSingleTextNotNull("balance");//账户余额
                                        String note = readXElement.getSingleTextNotNull("info3").trim();
                                        detail.usage = note;
                                        detail.abstr = pickupAbstr(note);
                                        detail.askNumber = readXElement.getSingleTextNotNull("corpSerial").trim();//支付流水号
                                        detail.originator = DateHelper.convertD10toD8(detail.tranDate) + detail.actNum + readXElement.getSingleTextNotNull("terminalNo").trim();//日期+账号+终端号=电子回单唯一匹配号
                                        detail.recAccNum = readXElement.getSingleTextNotNull("opAccNo").trim();
                                        detail.recAccName = readXElement.getSingleTextNotNull("info2").trim();
                                        detail.recAccBank = readXElement.getSingleTextNotNull("opBankName").trim();
                                        String cdFlag = readXElement.getSingleTextNotNull("dcFlag").trim();//借贷标识
                                        String amount = readXElement.getSingleTextNotNull("amount").trim();//金额
                                        if (amount.contains("-")) {
                                            if ("D".equals(cdFlag)) {
                                                detail.cdFlag = "2";
                                            } else if ("C".equals(cdFlag)) {
                                                detail.cdFlag = "1";
                                            }
                                            detail.tranAmt = amount.substring(1);
                                        } else {
                                            if ("D".equals(cdFlag)) {
                                                detail.cdFlag = "1";
                                            } else if ("C".equals(cdFlag)) {
                                                detail.cdFlag = "2";
                                            }
                                            detail.tranAmt = amount;
                                        }
                                        retAtsTrans.writeRetDetail(detail);
                                    }
                                } else {
                                    tmpRespCode = "0";
                                    tmpRespInfo = "根据查询条件没有得到对象记录";
                                }
                            } else {//受理未响应或受理失败
                                tmpRespCode = "-1";
                                tmpRespInfo = respCode + "：" + respInfo;
                                pageResult = true;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            pageResult = true;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = resutlt[1];
                        pageResult = true;
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception ex) {
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
            WriteBankLogLn("查询明细异常:" + ex);
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        return "1".equals(getBankConfig().getValueAsString("channelFlag")) ? d_7515_TodayTrans_Xml(p_req7515) : d_7515_TodayTrans_MT(p_req7515);
    }

    public RetAtsTrans d_7515_TodayTrans_MT(Req7515TodayTrans p_req7515) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7515.reqHeader);
        //写返回ATS的统一头部信息
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();
        try {
            String accNum = p_req7515.actNum;
            String date = Format.Date8Format.format(new Date());
            String dealedPath = getBankConfig().getValueAsString("DealedPath") + File.separator + date +
                    File.separator + "MT942" + File.separator + accNum + "_7515.txt";
            if (FileHelper.existFile(dealedPath)) {
                InputStreamReader isr = null;
                FileInputStream fis = null;
                BufferedReader reader = null;
                try {
                    fis = new FileInputStream(dealedPath);
                    isr = new InputStreamReader(fis, "UTF-8");
                    reader = new BufferedReader(isr);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                } finally {
                    if (reader != null) {
                        reader.close();
                    }
                    if (isr != null) {
                        isr.close();
                    }
                    if (fis != null) {
                        fis.close();
                    }
                }
                String readLine = "";
                while ((readLine = reader.readLine()) != null) {
                    // 账号 | 币种 | 交易日期| 交易时间| 计息日期 | 交易金额 |借贷标识| 账户余额 |对方账号|
                    // 对方户名 | 对方银行 |用途 | 流水号|
                    String[] transDetail = readLine.split("\\|");
                    if (transDetail.length > 12) {
                        RetAtsTransDetail detail = new RetAtsTransDetail();
                        detail.actArea = p_req7515.actArea;
                        detail.actNum = transDetail[0].trim();
                        detail.cur = convertCurToATS(transDetail[1].trim());
                        detail.tranDate = transDetail[2].trim();
                        detail.tranTime = transDetail[3].trim();
                        detail.valueDate = transDetail[4].trim();
                        detail.tranAmt = transDetail[5].trim();
                        detail.cdFlag = "C".equals(transDetail[6].trim()) ? "2" : "1";
                        detail.recAccNum = transDetail[8].trim();
                        detail.accBal = transDetail[7].trim();
                        detail.recAccBank = transDetail[10].trim();
                        detail.recAccName = transDetail[9].trim();
                        String[] transArray = transDetail[11].split("##");
                        if (transArray.length > 1) {
                            if (transArray[0].trim().length() > 256) {
                                detail.usage = transArray[0].trim().substring(0, 256);
                                detail.comment = transArray[0].trim().substring(256) + " " + transArray[1];
                            } else {
                                detail.usage = transArray[0].trim();
                                detail.comment = transArray[1];
                            }
                        } else {
                            if (transArray[0].trim().length() > 256) {
                                detail.usage = transArray[0].trim().substring(0, 256);
                                detail.comment = transArray[0].trim().substring(256);
                            } else {
                                detail.usage = transArray[0].trim();
                            }
                        }
                        detail.askNumber = transDetail[12].trim();
                        retAts.writeRetDetail(detail);
                    }
                }
                reader.close();
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
            WriteBankLogLn("查询今日明细异常：" + e);
        }
        if ("-1".equals(tmpRespCode)) {
            retAts = new RetAtsTrans(p_req7515.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("明细为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    public RetAtsTrans d_7515_TodayTrans_Xml(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }
}
